/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cronos.applicationmetric;

import cronos.dao.DAO;
import cronos.metric.Metric;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Leonardo Oliveira Moreira
 */
public class ApplicationMetricDAO extends DAO {

    public ApplicationMetricDAO() throws SQLException {
    }

    public void insert(ApplicationMetric applicationMetric) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO application_metric (application_id, metric_id) VALUES (?, ?)");
        preparedStatement.setLong(1, applicationMetric.getApplication().getId());
        preparedStatement.setLong(2, applicationMetric.getMetric().getId());
        int result = preparedStatement.executeUpdate();
        if (result == 1) {
            connection.commit();
        } else {
            connection.rollback();
        }
    }

    public void delete(ApplicationMetric applicationMetric) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM application_metric WHERE application_id = ? AND metric_id = ?");
        preparedStatement.setLong(1, applicationMetric.getApplication().getId());
        preparedStatement.setLong(2, applicationMetric.getMetric().getId());
        int result = preparedStatement.executeUpdate();
        if (result == 1) {
            connection.commit();
        } else {
            connection.rollback();
        }
    }
    
    public List<Metric> getMetricsByApplicationId(Integer id) throws SQLException {
        List<Metric> result = new ArrayList<Metric>();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT a.application_id, a.metric_id, b.name as metric_name FROM application_metric a, metric b WHERE a.application_id = ? AND a.metric_id = b.id ORDER BY b.name ASC");
            preparedStatement.setInt(1, id);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet != null && resultSet.next()) {
                Metric metric = new Metric();
                metric.setId(resultSet.getInt("metric_id"));
                metric.setName(resultSet.getString("metric_name"));
                result.add(metric);
            }
            resultSet.close();
            preparedStatement.close();
            connection.commit();
        } catch (SQLException ex) {
            connection.rollback();
            throw ex;
        }
        return result;
    }

}